<?php
/**
 * XSS Filter - Default
 *
 * <code>
 * $sString utilXssDefault::filter('<SCRIPT name="name"></SCRIPT>');
 * </code>
 *
 * @package util
 * @subpackage xss
 *
 * @author jylee3@simplexi.com
 * @version 1.0
 */
class utilXssDefault
{
    const RA_ATTRIBUTE = 0x01;
    const RA_PROTOCOL = 0x02;
    const RA_TAG = 0x03;

    /**
     * XSS | SQL Filter - Default
     *
     * <code>
     * $sString = utilXssDefault::filter('<SCRIPT name="name"></SCRIPT>');
     *
     * or
     *
     * $sString = utilXssDefault::filter("1134896409234' UNION SELECT '1', userid, userpw FROM user_t WHERE userid = 'test'  ORDER BY boardno ASC");
     * </code>
     *
     * @param    String    $sVal
     * @param    String    $sReplaceString
     *
     * @return    String
     */
    public static function filter($sVal, $sReplaceString = '<x>')
    {
        return utilSplClass::load('utilXssDefault')->RemoveXSS($sVal, $sReplaceString);
    }

    protected $sSearchHexEncodings = '/&#[xX]0{0,8}(21|22|23|24|25|26|27|28|29|2a|2b|2d|2f|30|31|32|33|34|35|36|37|38|39|3a|3b|3d|3f|40|41|42|43|44|45|46|47|48|49|4a|4b|4c|4d|4e|4f|50|51|52|53|54|55|56|57|58|59|5a|5b|5c|5d|5e|5f|60|61|62|63|64|65|66|67|68|69|6a|6b|6c|6d|6e|6f|70|71|72|73|74|75|76|77|78|79|7a|7b|7c|7d|7e);?/ie';
    protected $sSearchUnicodeEncodings = '/&#0{0,8}(33|34|35|36|37|38|39|40|41|42|43|45|47|48|49|50|51|52|53|54|55|56|57|58|59|61|63|64|65|66|67|68|69|70|71|72|73|74|75|76|77|78|79|80|81|82|83|84|85|86|87|88|89|90|91|92|93|94|95|96|97|98|99|100|101|102|103|104|105|106|107|108|109|110|111|112|113|114|115|116|117|118|119|120|121|122|123|124|125|126);?/ie';

    /* now the only remaining whitespace attacks are \t, \n, and \r */
    //protected $aRemainingAttack = array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'style', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base', 'onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');
    protected $sRemainingAttack = "javascript|vbscript|expression|applet|meta|xml|blink|link|style|script|embed|object|iframe|frame|frameset|ilayer|layer|bgsound|title|base|onabort|onactivate|onafterprint|onafterupdate|onbeforeactivate|onbeforecopy|onbeforecut|onbeforedeactivate|onbeforeeditfocus|onbeforepaste|onbeforeprint|onbeforeunload|onbeforeupdate|onblur|onbounce|oncellchange|onchange|onclick|oncontextmenu|oncontrolselect|oncopy|oncut|ondataavailable|ondatasetchanged|ondatasetcomplete|ondblclick|ondeactivate|ondrag|ondragend|ondragenter|ondragleave|ondragover|ondragstart|ondrop|onerror|onerrorupdate|onfilterchange|onfinish|onfocus|onfocusin|onfocusout|onhelp|onkeydown|onkeypress|onkeyup|onlayoutcomplete|onload|onlosecapture|onmousedown|onmouseenter|onmouseleave|onmousemove|onmouseout|onmouseover|onmouseup|onmousewheel|onmove|onmoveend|onmovestart|onpaste|onpropertychange|onreadystatechange|onreset|onresize|onresizeend|onresizestart|onrowenter|onrowexit|onrowsdelete|onrowsinserted|onscroll|onselect|onselectionchange|onselectstart|onstart|onstop|onsubmit|onunload";
    protected $aRemainingAttack_ATTRIBUTE = array('style', 'onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');
    protected $aRemainingAttack_PROTOCOL = array('javascript', 'vbscript', 'expression');
    protected $aRemainingAttack_TAG = array('applet', 'meta', 'xml', 'blink', 'link', 'style', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base');

    public function __construct() {}

    /**
     * SQL Filter - RemoveSql
     *
     * <code>
     * $utilXssDefault = new utilXssDefault();
     * $sString = $utilXssDefault->RemoveSql("1134896409234' UNION SELECT '1', userid, userpw FROM user_t WHERE userid = 'test'  ORDER BY boardno ASC");
     * </code>
     *
     * @param    String    $sVal
     *
     * @return    String
     */
    public function RemoveSql($sVal)
    {
        return preg_replace('/UNION|SELECT|DELETE|INSERT|UPDATE|DROP/i', '', $sVal);
    }

    /**
     * XSS Filter - RemoveXSS
     *
     * <code>
     * $utilXssDefault = new utilXssDefault();
     * $sString = $utilXssDefault->RemoveXSS('<SCRIPT name="name"></SCRIPT>');
     * </code>
     *
     * @param    String    $sVal
     * @param    String    $sReplaceString
     *
     * @return    String
     */
    public function RemoveXSS($sVal, $sReplaceString)
    {
        // don't use empty $replaceString because then no XSS-remove will be done
        if (empty($sReplaceString))    $sReplaceString = '<x>';

        // remove all non-printable characters. CR(0a) and LF(0b) and TAB(9) are allowed
        // this prevents some character re-spacing such as <java\0script>
        // note that you have to handle splits with \n, \r, and \t later since they *are* allowed in some inputs
        $sVal = preg_replace('/([\x00-\x08][\x0b-\x0c][\x0e-\x19])/', '', $sVal);

        // straight replacements, the user should never need these since they're normal characters
        // this prevents like <IMG SRC=&#X40&#X61&#X76&#X61&#X73&#X63&#X72&#X69&#X70&#X74&#X3A&#X61&#X6C&#X65&#X72&#X74&#X28&#X27&#X58&#X53&#X53&#X27&#X29>
        while (preg_match($this->sSearchHexEncodings, $sVal) || preg_match($this->sSearchUnicodeEncodings, $sVal)) {
            $sVal = preg_replace($this->sSearchHexEncodings, "chr(hexdec('\\1'))", $sVal);
            $sVal = preg_replace($this->sSearchUnicodeEncodings, "chr('\\1')", $sVal);
        }

        //remove the potential &#xxx; stuff for testing
        $sVal2 = preg_replace('/(&#[xX]?0{0,8}(9|10|13|a|b);)*\s*/i', '', $sVal);
        $aRemainingAttack = array();

        //stripos is faster than the regular expressions used later
        //and because the words we're looking for only have chars < 0x80
        //we can use the non-multibyte safe version
        if (preg_match_all("/".$this->sRemainingAttack."/i", $sVal2, $aRemainingAttackMatchs)>0) {
            if (!empty($aRemainingAttackMatchs) && is_array($aRemainingAttackMatchs[0])) {
                $aRemainingAttackMatchsUnique = array_unique($aRemainingAttackMatchs[0]);

                foreach ($aRemainingAttackMatchsUnique as $sRemainingAttackWord) {
                    $sRemainingAttackWord = strtolower($sRemainingAttackWord);

                    //keep list of potential words that were found
                    if (in_array($sRemainingAttackWord, $this->aRemainingAttack_PROTOCOL)) {
                        $aRemainingAttack[] = array($sRemainingAttackWord, self::RA_PROTOCOL);
                    }
                    if (in_array($sRemainingAttackWord, $this->aRemainingAttack_TAG)) {
                        $aRemainingAttack[] = array($sRemainingAttackWord, self::RA_TAG);
                    }
                    if (in_array($sRemainingAttackWord, $this->aRemainingAttack_ATTRIBUTE)) {
                        $aRemainingAttack[] = array($sRemainingAttackWord, self::RA_ATTRIBUTE);
                    }
                    //some keywords appear in more than one array
                    //these get multiple entries in $ra, each with the appropriate type
                }
            }
        }

        //only process potential words
        if (count($aRemainingAttack) > 0) {

            // keep replacing as long as the previous round replaced something
            $bFound = true;

            while ($bFound == true) {
                $sValBefore = $sVal;

                for ($i=0; $i<sizeof($aRemainingAttack); $i++) {
                    $sPattern = '';

                    for ($j=0; $j<strlen($aRemainingAttack[$i][0]); $j++) {
                        if ($j>0) {
                            $sPattern .= '((&#[xX]0{0,8}([9ab]);)|(&#0{0,8}(9|10|13);)|\s)*';
                        }

                        $sPattern .= $aRemainingAttack[$i][0][$j];
                    }

                    //handle each type a little different (extra conditions to prevent false positives a bit better)
                    switch ($aRemainingAttack[$i][1]) {
                        case self::RA_PROTOCOL :
                            //these take the form of e.g. 'javascript:'
                            $sPattern .= '((&#[xX]0{0,8}([9ab]);)|(&#0{0,8}(9|10|13);)|\s)*(?=:)';
                            break;
                        case self::RA_TAG :
                            //these take the form of e.g. '<SCRIPT[^\da-z] ....';
                            $sPattern = '(?<=<)'.$sPattern.'((&#[xX]0{0,8}([9ab]);)|(&#0{0,8}(9|10|13);)|\s)*(?=[^\da-z])';
                            break;
                        case self::RA_ATTRIBUTE :
                            //these take the form of e.g. 'onload='  Beware that a lot of characters are allowed
                            //between the attribute and the equal sign!
                            $sPattern .= '[\s\!\#\$\%\&\(\)\*\~\+\-\_\.\,\:\;\?\@\[\/\|\\\\\]\^\`]*(?==)';
                            break;
                    }

                    $sPattern = '/' . $sPattern . '/i';
                    // add in <x> to nerf the tag
                    $sReplacement = substr_replace($aRemainingAttack[$i][0], $sReplaceString, 2, 0);

                    // filter out the hex tags
                    $sVal = preg_replace($sPattern, $sReplacement, $sVal);

                    if ($sValBefore == $sVal) {
                         // no replacements were made, so exit the loop
                         $bFound = false;
                    }
                }
            }
        }

        return $sVal;
    }
}